import axios, { AxiosInstance, AxiosResponse } from 'axios'
import { IncomingMessage } from 'http'
import { getCookie } from 'cookies-next'
import https from 'https'
import { NextRouter } from 'next/router'
import { storagePrefix } from '@/shared/utils'
export interface CommonResponse {
  code: number
  message: string
  data: any
}

const baseURL = `${process.env.NEXT_PUBLIC_API_HOST}`
const timeout = 60000

const instance = axios.create({
  baseURL,
  timeout,
})

const setInterceptorsRes = (instance: AxiosInstance) => {
  instance.interceptors.response.use(
    (response) => {
      const { code, data, message } = response.data
      if (code === 0) return data
      if (code === -1) {
        // alert(message)
        return Promise.reject(response.data as AxiosResponse<CommonResponse>)
      }
      // 其他业务侧异常状态码
      return response.data
    },
    (error) => {
      console.log('error-res-server: ', JSON.stringify(error.message))
      return Promise.reject(error)
    }
  )
}

instance.interceptors.request.use((config) => {
  config.headers['source'] = 'web'
  config.headers['lang'] =
    config.params?.lang || getCookie(storagePrefix('locale'))
  config.headers['vToken'] = getCookie(storagePrefix('visitorId'))
  const accessToken = getCookie(storagePrefix('token'))
  accessToken && (config.headers.Authorization = `Bearer ${accessToken}`)
  return config
})

setInterceptorsRes(instance)

export default instance

export const serverIO = (
  req: IncomingMessage | undefined,
  router?: NextRouter
) => {
  const serverAxios = axios.create({
    baseURL,
    timeout,
  })

  serverAxios.interceptors.request.use(
    (config) => {
      config.headers['source'] = 'web'
      config.headers['lang'] = router?.locale
      config.headers['vToken'] = getCookie(storagePrefix('visitorId'), { req })
      const accessToken = getCookie(storagePrefix('token'), { req })
      accessToken && (config.headers.Authorization = `Bearer ${accessToken}`)
      config.httpsAgent = new https.Agent({ rejectUnauthorized: false })

      return config
    },
    (error) => {
      console.log('error-req-server: ', JSON.stringify(error.message))
      return Promise.reject(error)
    }
  )

  setInterceptorsRes(serverAxios)

  return serverAxios
}
